package pipeline

import (
	"alarm-flow/datasource"
	"context"
	"encoding/json"
	"fmt"
	"time"
)

const (
	AlarmConfigPrefix      = "alarm_flow_alarm_config_"
	AlarmMeasurementPrefix = "alarm_flow_alarm_measurement_"
	CollectInstPrefix      = "alarm_flow_collect_inst_"
	PushConfigPrefix       = "alarm_flow_push_config_"
)

func setInstState(cmdbInstId int64, measurement, field, state string) (err error) {
	var redisCli = datasource.RedisCli
	key := fmt.Sprintf("%s_%d_%s_%s", CollectInstPrefix, cmdbInstId, measurement, field)
	val := RedisInstState{State: state, Timestamp: time.Now().UnixMilli()}
	res := redisCli.Set(context.Background(), key, val, 0)
	return res.Err()
}

func getInstState(cmdbInstId int64, measurement, field string) (state *RedisInstState, err error) {
	var redisCli = datasource.RedisCli
	state = new(RedisInstState)

	key := fmt.Sprintf("%s_%d_%s_%s", CollectInstPrefix, cmdbInstId, measurement, field)
	res := redisCli.Get(context.Background(), key)
	if res.Err() == nil {
		return
	}

	err = json.Unmarshal([]byte(res.Val()), state)
	return
}

func getMeasurementFields(measurement string) (fields []string, err error) {
	var redisCli = datasource.RedisCli
	key := fmt.Sprintf("%s_%s", AlarmMeasurementPrefix, measurement)
	res := redisCli.SMembers(context.Background(), key)
	if res.Err() != nil {
		return
	}
	fields = res.Val()
	return
}

func addMeasurementField(measurement string, field string) (err error) {
	var redisCli = datasource.RedisCli
	key := fmt.Sprintf("%s_%s", AlarmMeasurementPrefix, measurement)
	res := redisCli.SAdd(context.Background(), key, field)
	return res.Err()
}

func getAlarmConfig(measurement, field string) (config *RedisAlarmConfig, err error) {
	var redisCli = datasource.RedisCli
	key := fmt.Sprintf("%s_%s_%s", AlarmConfigPrefix, measurement, field)
	res := redisCli.Get(context.Background(), key)
	if res.Err() != nil {
		err = fmt.Errorf("can not find redis key %s", key)
		return
	}

	config = new(RedisAlarmConfig)
	err = json.Unmarshal([]byte(res.Val()), config)
	return
}

func setAlarmConfig(config RedisAlarmConfig) (err error) {
	var redisCli = datasource.RedisCli
	key := fmt.Sprintf("%s_%s_%s", AlarmConfigPrefix, config.Measurement, config.Field)
	res := redisCli.Set(context.Background(), key, config, 0)
	fmt.Println(111, config)
	return res.Err()
}
